package in.muton.edushare.poll.pages;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.dynamicWebResources.ExcelResource;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.deptpages.DeptBase;
import in.muton.edushare.poll.panels.PollList;
import in.muton.edushare.poll.reports.excel.ExcelReport;
import in.muton.edushare.poll.util.PollURLHelper;
import in.muton.edushare.url.EduShareURLPanel;
import in.muton.edushare.wicket.models.CayenneModel;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.PageParameters;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.ResourceLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.dao.PollsDAO;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.util.StringUtil;
import com.edushare.common.util.URLUtils;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.PollPages;
import com.edushare.common.vo.PollQuestions;
import com.edushare.common.vo.UserPoll;
import com.edushare.common.vo.Users;

public abstract class PollBase extends EduShareBasePage {

	private static Log log = LogFactory.getLog(PollBase.class);
	public static final String[] pageNames = { "PollEdit", "PollView",
			"PollResults" };

	public PollBase(PageParameters params) {
		add(CSSPackageResource
				.getHeaderContribution(PollList.class, "Poll.css"));
		add(CSSPackageResource.getHeaderContribution(DeptBase.class,
				"deptHome.css"));

		Poll p = new PollsDAO(getSessionORMInterface()).getPollById(params
				.getAsInteger("0", 0));
		if (p != null) {
			setPollModel(new CayenneModel<Poll>(p));
			upgradePoll(p);
		}

		add(new ResourceLink<Void>("printReport", new ExcelResource() {
			@Override
			protected byte[] getExcel() {
				try {
					return ExcelReport.generateFullReport(getPollModel()
							.getObject());
				} catch (IOException e) {
					log
							.fatal(
									"Fatal error during report generation of poll. Poll ID: "
											+ getPollModel().getObject()
													.getPollId(), e);
					throw new EduShareRuntimeException();
				}
			}

			@Override
			protected String getFileName() {
				String pollName = getPollModel().getObject().getPollName();
				if (StringUtil.isValid(pollName)) {
					if (pollName.length() > 100) {
						pollName = pollName.substring(0, 90);
					}
					return URLUtils.escapeSplCharsFromFileName(pollName)
							+ ".xls";
				} else {
					return "Poll-Report-"
							+ getPollModel().getObject().getPollId() + ".xls";
				}
			}
		}){
			private static final long serialVersionUID = -245834605980708022L;
			@Override
			public boolean isVisible() {
				return getPageName().equals(PollResults.POLL_RESULT_STRING);
			}
		});

		add(new EduShareURLPanel("creator", new CayenneModel<Users>(
				p == null ? getLoggedInUser() : p.getCreator())));
		add(new Label("pollName", p == null ? "New Poll" : p.getPollName()));
		init();
	}

	private void init() {
		String page = getPageName();
		Poll poll = null;
		if (pollModel != null)
			poll = pollModel.getObject();
		for (String p : pageNames) {
			WebMarkupContainer wmc = new WebMarkupContainer(p);
			add(wmc);
			if (page.equals(p))
				wmc.add(new AttributeAppender("class", new Model<String>(
						"es-selected"), " "));

			if (p.equals("PollEdit")) {
				if (poll == null)
					wmc.add(new DummyLink("link"));
				else
					wmc.add(PollURLHelper
							.getEditPageURL("link", getPollModel()));
				wmc.setVisible(poll == null
						|| getLoggedInUser() == poll.getCreator());
			} else if (p.equals(PollResults.POLL_RESULT_STRING)) {
				if (poll == null)
					wmc.add(new DummyLink("link"));
				else
					wmc.add(PollURLHelper.getResultPageURL("link",
							getPollModel()));
				if (poll == null || poll.getStatus() == Poll.POLL_STATUS_DRAFT)
					wmc.setVisible(false);
			} else if (p.equals("PollView")) {
				if (poll == null) {
					wmc.add(new DummyLink("link"));
					wmc.setVisible(false);
					continue;
				}
				wmc.add(PollURLHelper.getPollAnswerPage("link", getPollModel(),
						true));
				List<Users> reviewers = new UserPollDAO(
						getSessionORMInterface()).getPollObservers(poll);
				boolean owner = reviewers.contains(getLoggedInUser())
						|| poll.getCreator() == getLoggedInUser();
				if (owner) {
					wmc.setVisible(true);
					continue;
				}
				List<Users> resp = new UserPollDAO(getSessionORMInterface())
						.getPollRespondents(pollModel.getObject());
				boolean respondent = resp.contains(getLoggedInUser());
				if (respondent) {
					int answerStatus = new UserPollDAO(getSessionORMInterface())
							.getPollStatus(getLoggedInUser(), pollModel
									.getObject());
					if (answerStatus == UserPoll.POLL_PENDING) {
						wmc.setVisible(true);
						continue;
					}
				}
				wmc.setVisible(false);
			}
		}
	}

	protected abstract String getPageName();

	@Override
	public String getPageTitle() {
		return getLoggedInUser().getCompleteUserName() + " | Polls | Edushare";
	}

	@Override
	public String getUserRole() {
		return "";
	}

	public void setPollModel(IModel<Poll> pollModel) {
		this.pollModel = pollModel;
	}

	public IModel<Poll> getPollModel() {
		return pollModel;
	}

	public static void upgradePoll(Poll poll) {
		if (poll.getPages().size() == 0) {
			PollsDAO pDAO = new PollsDAO(EduShareSession.get()
					.getSessionORMInterface());
			PollPages p = pDAO.addNewPage(poll, "First Page", 1);
			List<PollQuestions> pqList = poll.getQuestions();
			for (PollQuestions pq : pqList) {
				pq.setPage(p);
			}
		}
	}

	public class DummyLink extends Link<Void> {
		private static final long serialVersionUID = 5511276709901709455L;

		public DummyLink(String id) {
			super(id);
		}

		@Override
		public void onClick() {
		}
	}

	private IModel<Poll> pollModel = null;
}
